<template>
  <div>
    <div class="app-container" style="padding-bottom: 0">
      <el-tabs v-model="activeName">
        <el-tab-pane label="发起审批" name="first"></el-tab-pane>
        <el-tab-pane label="查看数据" name="second"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="mt10">
      <component :is="componentName" :flowData="flowData" :deptOptions="deptOptions" @checkExamine="checkExamine"
                 :flowline="flowline" :workDay="workDay" :workType="workType" ref="examinbody" @reset="reset"/>
      <div class="app-container mt10" v-if="activeName=='first'">
        <el-form label-width="80px" label-position="left">
          <div class="examineTitle mb20">
            流程
          </div>
          <el-row v-if="flowline">
            <el-col>
              <el-timeline>
                <el-timeline-item
                  v-for="(item, index) in flowline"
                  :key="index">
                  <div class="conent-timeline">
                    <div class="conent-timeline-l">
                      <p>{{ item.exaName }}</p>
                      <p>{{item.userData?item.userData.length:0}}人审核</p>
                    </div>
                    <div class="conent-timeline-r" v-if="item.userData">
                      <div class="conent-timeline-r-list" v-for="examin in item.userData">
                        <img src="@/assets/images/userdefult.jpg" alt="">
                        <p>{{examin.name}}</p>
                      </div>
                    </div>
                  </div>
                </el-timeline-item>
              </el-timeline>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import leaveAdd from './leave/add'
import leaveTable from './leave/table'
import overtimeAdd from './overtime/add'
import overtimeTable from './overtime/table'
import cardReplacementAdd from './card_replacement/add'
import cardReplacementTable from './card_replacement/table'
import {mapGetters} from 'vuex'
import {listFlow} from '@/api/system/design.js'
import {deptTreeAll} from '@/api/system/user'
import {attend_group_user} from "@/api/system/sign_category"
import {getDept} from "@/api/system/dept";

export default {
  name: "index",
  components: {
    leaveAdd,
    leaveTable,
    overtimeAdd,
    overtimeTable,
    cardReplacementAdd,
    cardReplacementTable
  },
  data() {
    return {
      activeName: '',
      componentName: '', // leaveTable leaveAdd
      addModule: '', // 发起审核
      flowData: null,
      deptOptions: [],
      depetUser: [], // 用户本身的部门链
      flowline: null,
      userTime: 0,
      workDay: null, // 适用排班信息
      examinLine: [],
      workType: 0, // 考勤类型 1 固定 2 排班
    }
  },
  computed: {
    ...mapGetters([
      'deptId',
      'company_id'
    ]),
  },
  created() {
    const flowId = this.$route.params && this.$route.params.flowId;
    this.examineFlowFn(flowId)
    this.getModule(flowId)
  },
  watch: {
    activeName() {
      this.componentName = this.componentName == `${this.addModule}Add` ? `${this.addModule}Table` : `${this.addModule}Add`
    }
  },
  methods: {
    onSubmit(){
      this.$refs.examinbody.onSubmit(this.flowline)
    },
    checklistLine(index) {
      let that = this
      if(index<this.examinLine.length){
        // assignedType==> 人工审批 ASSIGN_USER 自动通过 AUTO_PASS
        // setApproval==>
        // 指定成员 ASSIGN_USER;
        // 发起人自己 SELF_SELECT;
        // 角色 ROLE;
        // 部门主管 DEPART_DIRECTOR 查询当前账号的组织主管
        // 发起人自选 OPTIONAL;直属主管 REPORTS_TO;
        // moreUserSign  会签所有审批人同意通过 AND；或签其中一人同意通过 OR
        let item = this.$deepCopy(this.examinLine[index])
        if (item.assignedType === 'ASSIGN_USER') {
          switch (item.setApproval) {
            case 'ASSIGN_USER':
              item.userData = item.assignedUser
              that.$set(this.examinLine, index, item)
              that.checklistLine(index + 1)
              break;
            case 'SELF_SELECT':
              break;
            case 'OPTIONAL':
              break;
            case 'ROLE':
              break;
            case 'REPORTS_TO':
              break;
            case 'DEPART_DIRECTOR':
              getDept(this.deptId).then(response => {
                item.userData = [{id: response.data.userId, name: response.data.leader}]
                that.$set(this.examinLine, index, item)
                that.checklistLine(index + 1)
              });
              break;
          }
        }else if(item.assignedType == 'CC'){
          item.userData = this.$deepCopy(item.assignedUser)
          that.$set(this.examinLine, index, item)
          that.checklistLine(index + 1)
        }
      }else{
        console.log('完成部署：', this.examinLine)
        this.flowline = this.$deepCopy(this.examinLine)
      }
    },
    // 获取用户适用的排班信息
    getUserAttend() {
      attend_group_user({deptIds: this.deptId}).then(res => {
        // type 1 固定班制 2 排班制
        this.workType = res.data.detail.type
        if (res.data.detail.type == 1) {
          this.workDay = res.data.signCategory
        }
      })
    },
    getModule(flowId) {
      let add_ = ''
      if (flowId == '11') {
        add_ = 'leave' // 请假发起审核
        this.getDeptTree()
        this.getUserAttend() // 获取用户对应考勤组
      }
      if (flowId == '12') {
        add_ = 'cardReplacement' // 补卡发起审核
        this.getUserAttend() // 获取用户对应考勤组
      }
      if (flowId == '13') {
        add_ = 'overtime' // 加班发起审核
        this.getUserAttend() // 获取用户对应考勤组
      }
      this.addModule = add_ // 发起审核
      this.activeName = 'first'
    },
    // 用户审核流程信息 examineFlow
    examineFlowFn(flowId) {
      listFlow({
        type: flowId,
        companyId: this.company_id
      }).then(res => {
        if (res.rows.length) {
          this.flowData = res.rows[0]
          if (flowId == '13' || flowId == '12') {
            this.getDeptTree(flowId)
          }
        }
      })
    },
    getDeptTree(flowId) {
      deptTreeAll().then(response => {
        this.deptOptions = response.data;
        if (flowId == '13' || flowId == '12') {
          this.checkExamine(0)
        }
      });
    },
    // 审批流程判断采集
    checkExamine(data) {
      console.log('时长：', data.data)
      let that = this
      this.unit = data.unit // 请假方式 // 单位 1-天 2-半天 3-小时
      this.userTime = data.data || 0
      this.depetUser = this.getItem(this.deptOptions) // 用户部门线上下级
      let flow_ = JSON.parse(that.flowData.flow)
      let flowline = that.$flowCheckFn(flow_.children, this.depetUser,  this.userTime)
      if (flowline) {
        this.examinLine = this.$deepCopy(flowline)
        this.checklistLine(0)
      }
    },
    // flowCheckFn(data) {
    //   // conditionType user
    //   let that = this
    //   if (data.type == "CONCURRENTS" || data.type == "CONDITIONS") {
    //     // 条件判断
    //     let condition_ = false
    //     let result = []
    //     for (let i = 0; i < data.branchs.length; i++) {
    //       const oItem = data.branchs[i]; // type "CONCURRENT" props conditionType
    //       if (condition_) {
    //         return
    //       }
    //       if (oItem.type == 'CONCURRENT' || oItem.type == "CONDITION") {
    //         // 判断条件类型  props conditionType user部门 time时长 type请假类型
    //         let isCan = false // 符合条件进入
    //         if (oItem.props.conditionType.indexOf('user') !== -1) {
    //           // 条件内的部门/人员 department_check_data
    //           let depart_ = [] // 符合条件的部门id
    //           let user_ = [] // 符合条件的职员id
    //           for (let item of oItem.props.department_check_data) {
    //             if (item.type == 'dept') {
    //               depart_.push(item.id)
    //             }
    //             if (item.type == 'user') {
    //               user_.push(item.id)
    //             }
    //           }
    //           // 如果是部门需要判定是否在他的子集下亦可以通过条件
    //           // 当前用户的部门id this.deptId，当前用户部门以及父级id this.depetUser
    //           if (depart_.indexOf(this.deptId) !== -1) {
    //             isCan = true
    //           } else {
    //             for (let deptItem of depart_) {
    //               if (this.depetUser.indexOf(deptItem) !== -1) {
    //                 isCan = true
    //               }
    //             }
    //           }
    //           if (user_.indexOf(this.userId) !== -1) {
    //             isCan = true
    //           }
    //         }
    //         if (oItem.props.conditionType.indexOf('time') !== -1) {
    //           console.log('判断时长')
    //           // timeType &lt;等于< ; &gt;=等于>=号
    //           // unit // 请假方式 // 单位 1-天 2-半天 3-小时
    //           // 用户当前请假时长 this.userTime
    //           // 非IN 使用 value,IN 使用区间  start_time start_value end_value leave_type
    //           if (oItem.props.timeType == '&lt;' && this.userTime < parseFloat(oItem.props.value)) {
    //             isCan = true
    //           }
    //           if (oItem.props.timeType == '&lt;=' && this.userTime <= parseFloat(oItem.props.value)) {
    //             isCan = true
    //           }
    //           if (oItem.props.timeType == '&gt;' && this.userTime > parseFloat(oItem.props.value)) {
    //             isCan = true
    //           }
    //           if (oItem.props.timeType == '&gt;=' && this.userTime >= parseFloat(oItem.props.value)) {
    //             isCan = true
    //           }
    //           if (oItem.props.timeType == '=' && this.userTime == parseFloat(oItem.props.value)) {
    //             isCan = true
    //           }
    //         }
    //         if (oItem.props.conditionType.indexOf('type') !== -1) {
    //           console.log('判断类型')
    //         }
    //         if (isCan) {
    //           // 条件通过进入下一步
    //           condition_ = true
    //           result = this.flowCheckFn(oItem.children)
    //           if (data.children && JSON.stringify(data.children) !== '{}') {
    //             if (that.flowCheckFn(data.children)) {
    //               result = result.concat(that.flowCheckFn(data.children))
    //             }
    //           }
    //           if (result) {
    //             return result;
    //           }
    //         }
    //       }
    //     }
    //   }
    //   // APPROVAL 审核人 CC 抄送人
    //   if (data.type == "APPROVAL" || data.type == "CC") {
    //     let data_ = JSON.parse(JSON.stringify(data.props))
    //     data_.exaName = data.name
    //     if (JSON.stringify(data.children) !== '{}') {
    //       const result = this.flowCheckFn(data.children)
    //       if (result) {
    //         return [data_].concat(result);
    //       }
    //     } else {
    //       return [data_];
    //     }
    //   }
    //   if (data.type == "EMPTY") {
    //     const result = this.flowCheckFn(data.children)
    //     if (result) {
    //       return result;
    //     }
    //   }
    // },
    getItem(data) {
      for (let i = 0; i < data.length; i++) {
        const oItem = data[i];
        if (oItem.id === 203) {
          return [oItem.id];
        } else {
          if (oItem.children && oItem.children.length) {
            const result = this.getItem(oItem.children);
            if (result) {
              return [oItem.id].concat(result);
            }
          }
        }
      }
    },
    reset(){
      this.flowline = null
    }
  }
}
</script>

<style scoped>
</style>
